package service

import (
	"chat/common"
	utils "chat/util"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"path"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

type Uploader struct {
}

func (u *Uploader) Upload(ctx *gin.Context) {
	file, _ := ctx.FormFile("file")
	if !strings.HasPrefix(file.Header.Get("Content-Type"), "image") {
		utils.Result(http.StatusBadRequest, "只能上传图片", ctx)
		return
	}
	unix := time.Now().Unix()
	basePath := fmt.Sprintf("%s/%s-%s", "static", strconv.Itoa(int(unix)), filepath.Base(file.Filename))
	err := ctx.SaveUploadedFile(file, basePath)
	if err != nil {
		return
	}
	getwd, err := os.Getwd()
	if err != nil {
		return
	}
	var now = time.Now().Format("2006-01-02")
	key := now + "/" + filepath.Base(file.Filename)
	if common.QiniuUploader(path.Join(getwd, "/", basePath), key) {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    http.StatusOK,
			"url":     common.BASEURL + "/" + key,
			"message": "上传成功",
		})
	} else {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"url":     nil,
			"message": "上传失败",
		})
	}
}
